import type { FormInstance } from 'element-plus'
import { ref } from 'vue'

export function useForm(submitApi: () => Promise<void>) {
  const formRef = ref<FormInstance>()
  const formLoading = ref(false)
  async function submitForm() {
    const isValidResult = await formRef.value?.validate().catch(() => false)
    if (!isValidResult || formLoading.value === true) {
      return
    }
    formLoading.value = true
    try {
      return await submitApi()
    }
    finally {
      formLoading.value = false
    }
  }

  function resetForm() {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }
  return { formRef, formLoading, submitForm, resetForm }
}
